<template>
  <s-clean-layout title="批量添加来往" navbar="normal">
    <view class="batch-container">
      
      <!-- 共有信息 -->
      <view class="common-info">      
        <!-- 日期选择 -->
        <view class="form-item" @tap="showDatePicker = true">
          <view class="item-label">来往日期</view>
          <view class="item-content">{{ formData.date }}</view>
          <view class="item-arrow">
            <uni-icons type="right" size="16" color="#ccc"></uni-icons>
          </view>
        </view>
        
        <!-- 每页人数 -->
        <view class="form-item">
          <view class="item-label">每页人数</view>
          <view class="item-content">
            <picker @change="onPersonCountChange" :value="personCountIndex" :range="personCountOptions">
              <view class="picker-value">{{ personCount }}</view>
            </picker>
          </view>
          <view class="item-arrow">
            <uni-icons type="right" size="16" color="#ccc"></uni-icons>
          </view>
        </view>
      </view>
      
      <!-- 批量输入列表 -->
      <view class="batch-list">
        <scroll-view scroll-y class="batch-scroll">
          <view 
            class="batch-item" 
            v-for="(item, index) in batchItems" 
            :key="index"
          >
            <view class="contact-icon" @tap="openContactSelector(index)">
              <uni-icons type="contact" size="24" color="#6d9ef8"></uni-icons>
            </view>
            <view class="item-col name-col">
              <input 
                type="text" 
                v-model="item.name" 
                :placeholder="`姓名 ${index + 1}`"
                placeholder-class="input-placeholder"
              />
            </view>
            <view class="item-col amount-col">
              <input 
                type="digit" 
                v-model="item.amount" 
                placeholder="金额"
                placeholder-class="input-placeholder"
              />
            </view>
            <view class="item-col gift-col">
              <input 
                type="text" 
                v-model="item.gift" 
                placeholder="礼品"
                placeholder-class="input-placeholder"
              />
            </view>
          </view>
        </scroll-view>
      </view>
      
      <!-- 底部固定操作栏 -->
      <view class="fixed-bottom">
        <view class="save-button-full" @tap="saveRecords">保存</view>
      </view>
      
      <!-- 日期选择器弹窗 -->
      <s-datetime-picker
          v-model:visible="showDatePicker"
          :title="'选择日期'"
          mode="date"
          :initial-date="formData.date"
          @confirm="onDateConfirm"
          @cancel="showDatePicker = false"
        />
      
      <!-- 通讯录选择器 -->
      <s-contact-selector
          v-model:visible="showContactSelector"
          :title="'选择联系人'"
          :multiple="false"
          @confirm="selectContact"
      />
    </view>
  </s-clean-layout>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import GiftApi from '@/pages/money/api/gift';

// 页面状态
const recordType = ref('receive');
const giftBookId = ref(0);

// 表单数据
const formData = ref({
  date: formatDate(new Date())
});

// 弹窗控制
const showDatePicker = ref(false);
const showContactSelector = ref(false);
const currentEditIndex = ref(-1);

// 每页人数选择
const personCountOptions = Array.from({length: 14}, (_, i) => (i + 2).toString());
const personCountIndex = ref(3);  // 默认选择5人（索引3对应值5）
const personCount = computed(() => parseInt(personCountOptions[personCountIndex.value]));

// 批量输入项
const batchItems = ref([]);

// 监听每页人数变化，更新批量输入项
watch(personCount, (newCount) => {
  updateBatchItems(newCount);
});

// 更新批量输入项
const updateBatchItems = (count) => {
  // 保留已有数据
  const currentItems = [...batchItems.value];
  
  // 创建新的批量输入项数组
  const newItems = [];
  for (let i = 0; i < count; i++) {
    if (i < currentItems.length) {
      // 保留已有数据
      newItems.push(currentItems[i]);
    } else {
      // 添加新的空项
      newItems.push({
        contactId: null,  // 默认值改为null
        name: '',
        amount: '',
        gift: ''
      });
    }
  }
  
  batchItems.value = newItems;
};

// 选择每页人数
const onPersonCountChange = (e) => {
  personCountIndex.value = e.detail.value;
};

// 打开通讯录选择器
const openContactSelector = (index) => {
  currentEditIndex.value = index;
  showContactSelector.value = true;
};

// 选择联系人
const selectContact = (contact) => {  
  if (currentEditIndex.value >= 0 && currentEditIndex.value < batchItems.value.length) {
    if (Array.isArray(contact) && contact.length > 0) {
      // 处理数组格式
      const selectedContact = contact[0];
      batchItems.value[currentEditIndex.value].contactId = parseInt(selectedContact.id);
      batchItems.value[currentEditIndex.value].name = selectedContact.name;
    } 
    else if (contact && contact.id) {
      // 处理单个对象格式
      batchItems.value[currentEditIndex.value].contactId = parseInt(contact.id);
      batchItems.value[currentEditIndex.value].name = contact.name;
    }
    else if (contact && contact.contact) {
      // 处理自定义格式
      batchItems.value[currentEditIndex.value].contactId = parseInt(contact.contact.id);
      batchItems.value[currentEditIndex.value].name = contact.contact.name;
    }
  }
  showContactSelector.value = false;
};

// 页面加载时获取路由参数
onMounted((options) => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const params = currentPage.options || {};
  if (params.bookId) {
    giftBookId.value = parseInt(params.bookId);
    recordType.value = params.bookType || 'receive';
  }
  
  // 确保页面加载时立即初始化批量输入项
  updateBatchItems(personCount.value);
});

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 日期确认
const onDateConfirm = (date) => {
  if (typeof date === 'object' && date !== null) {
    if (date.date) {
      formData.value.date = date.date;
    } else if (date instanceof Date) {
      formData.value.date = formatDate(date);
    } else {
      console.log('日期选择返回:', date);
      formData.value.date = JSON.stringify(date);
    }
  } else {
    formData.value.date = date;
  }
  showDatePicker.value = false;
};

// 保存记录
const saveRecords = async () => {
  // 验证数据：姓名必填，金额或礼品至少填一个
  const validItems = batchItems.value.filter(item => 
    item.name && (item.amount || item.gift)
  );
  
  if (validItems.length === 0) {
    uni.showToast({
      title: '请至少填写一条有效记录（姓名必填，金额或礼品至少填一个）',
      icon: 'none'
    });
    return;
  }
  
  try {
    uni.showLoading({
      title: '保存中...'
    });
    
    // 构建请求参数
    const params = {
      accountBookId: giftBookId.value,
      giftDate: formData.value.date,
      giftList: validItems.map(item => ({
        contactName: item.name,
        contactId: item.contactId || null,  // 如果没有contactId则传null
        giftAmount: item.amount ? parseFloat(item.amount) : 0,
        giftItem: item.gift || ''
      }))
    };
    
    // 调用批量添加接口
    const res = await GiftApi.batchAddAccountBookGift(params);
    
    uni.hideLoading();
    
    if (res.code === 0) {
      uni.showToast({
        title: '保存成功',
        icon: 'success',
        duration: 1500,
        success: () => {
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        }
      });
    } else {
      uni.showToast({
        title: res.msg || '保存失败',
        icon: 'none'
      });
    }
  } catch (error) {
    uni.hideLoading();
    console.error('保存批量记录失败:', error);
    uni.showToast({
      title: '网络异常，请稍后重试',
      icon: 'none'
    });
  }
};

// 格式化日期
function formatDate(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}
</script>

<style lang="scss" scoped>
.batch-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f5f5f5;
}

.nav-bar {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #fff;
  border-bottom: 1px solid #eee;
  height: 88rpx;
}

.back-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.page-title {
  flex: 1;
  font-size: 32rpx;
  color: #333;
  text-align: center;
}

.save-btn {
  padding: 0 20rpx;
  font-size: 28rpx;
  color: #333;
}

.common-info {
  background-color: #fff;
  margin-top: 20rpx;
  padding: 0 30rpx;
}

.section-title {
  display: block;
  padding: 20rpx 0;
  font-size: 28rpx;
  color: #999;
}

.form-item {
  display: flex;
  align-items: center;
  padding: 30rpx 0;
  border-bottom: 1px solid #f5f5f5;
}

.item-label {
  width: 180rpx;
  font-size: 28rpx;
  color: #333;
}

.item-content {
  flex: 1;
  font-size: 28rpx;
  color: #333;
}

.item-arrow {
  width: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.picker-value {
  font-size: 28rpx;
  color: #333;
}

.batch-list {
  flex: 1;
  margin-top: 20rpx;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  padding-top: 20rpx;
}

.batch-scroll {
  flex: 1;
  height: 0;
}

.batch-item {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  border-bottom: 1px solid #f5f5f5;
}

.contact-icon {
  width: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.item-col {
  display: flex;
  align-items: center;
  margin-right: 20rpx; /* 添加右侧间距 */
}

.name-col {
  flex: 2;
}

.amount-col {
  flex: 1;
  margin-left: 10rpx; /* 添加左侧间距 */
}

.gift-col {
  flex: 1;
  margin-left: 10rpx; /* 添加左侧间距 */
}

.item-col input {
  width: 100%;
  height: 60rpx;
  font-size: 28rpx;
  color: #333;
  background-color: #f8f8f8; /* 添加背景色以区分不同输入框 */
  border-radius: 6rpx; /* 添加圆角 */
  padding: 0 10rpx; /* 添加内边距 */
}

.input-placeholder {
  color: #ccc;
}

.fixed-bottom {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  background-color: #fff;
  border-top: 1px solid #eee;
  padding: 20rpx;
  z-index: 100;
}

.save-button-full {
  width: 100%;
  height: 80rpx;
  background-color: #ff6b6b;
  color: #fff;
  border-radius: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32rpx;
  font-weight: bold;
}
</style>